<template>
  <div class="dish-information-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">菜品信息管理</span>
          <el-button type="primary" @click="handleAdd">添加菜品</el-button>
        </div>
      </template>

      <!-- 搜索和过滤区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchQuery"
              placeholder="请输入菜品名称搜索"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterType" placeholder="菜品类型" clearable>
              <el-option
                v-for="type in dishTypes"
                :key="type.dtId"
                :label="type.dtName"
                :value="type.dtId"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="菜品状态" clearable>
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button @click="resetSearch" style="margin-left: -150px;">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <table class="dish-table">
          <thead>
            <tr>
              <th>编号</th>
              <th>图片</th>
              <th>菜品名称</th>
              <th>价格</th>
              <th>类型</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredDishes" :key="item.dishId">
              <td>{{ item.dishId }}</td>
              <td>
                <el-image
                  :src="ossUrl(item.dishImage)"
                  :preview-src-list="[ossUrl(item.dishImage)]"
                  :initial-index="0"
                  fit="cover"
                  class="dish-image"
                  preview-teleported
                  @click="handlePreview(item)"
                ></el-image>
              </td>
              <td>{{ item.dishName }}</td>
              <td>￥{{ item.price }}</td>
              <td>{{ item.typeName }}</td>
              <td>
                <el-tag :type="getStatusType(item.dishStatus)">
                  {{ getStatusLabel(item.dishStatus) }}
                </el-tag>
              </td>
              <td class="actions-column">
                <div class="action-buttons">
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleEdit(item)"
                  >
                    编辑
                  </el-button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加菜品' : '编辑菜品'"
      width="50%"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="菜品图片" prop="dishImage">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="customUpload"
          >
            <img v-if="form.dishImage" :src="form.dishImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="form.dishName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="菜品类型" prop="dtId">
          <el-select v-model="form.dtId" placeholder="请选择菜品类型">
            <el-option
              v-for="type in dishTypes"
              :key="type.dtId"
              :label="type.dtName"
              :value="type.dtId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品状态" prop="dishStatus">
          <el-select v-model="form.dishStatus" placeholder="请选择菜品状态">
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品描述" prop="dishDescribe">
          <el-input
            v-model="form.dishDescribe"
            type="textarea"
            :rows="4"
            placeholder="请输入菜品描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps } from 'element-plus'
import { dishApi, dishTypeApi } from '../api/console'

// 接口类型定义
interface DishType {
  dtId: number
  dtName: string
}

interface Dish {
  dishId: number
  dishImage: string
  dishName: string
  price: number
  dishStatus: number
  dtId: number
  typeName: string
  dishDescribe: string
}

// 状态定义
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const searchQuery = ref('')
const filterType = ref<number | ''>('')
const filterStatus = ref<number | ''>('')
const dishes = ref<Dish[]>([])
const dishTypes = ref<DishType[]>([])
const formRef = ref<FormInstance>()

// 菜品状态选项
const statusOptions = [
  { value: 0, label: '出售中' },
  { value: 1, label: '售空' },
  { value: 2, label: '已下架' }
]

// 表单数据
const form = ref({
  dishId: 0,
  dishImage: '',
  dishName: '',
  price: 0,
  dishStatus: 0,
  dtId: undefined as number | undefined,
  dishDescribe: ''
})

// 表单验证规则
const rules = {
  dishName: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入菜品价格', trigger: 'blur' }
  ],
  dtId: [
    { required: true, message: '请选择菜品类型', trigger: 'change' }
  ],
  dishStatus: [
    { required: true, message: '请选择菜品状态', trigger: 'change' }
  ]
}

// 计算属性：过滤后的菜品列表
const filteredDishes = computed(() => {
  return dishes.value.filter(dish => {
    const nameMatch = dish.dishName.toLowerCase().includes(searchQuery.value.toLowerCase())
    const typeMatch = !filterType.value || (dish.dtId) === filterType.value
    const statusMatch = filterStatus.value === '' || dish.dishStatus === Number(filterStatus.value)
    return nameMatch && typeMatch && statusMatch
  })
})

// 获取菜品列表
const fetchDishes = async () => {
  try {
    loading.value = true
    const response = await dishApi.getAllDishes()
    if (response.code === 200) {
      // 为每个菜品添加类型名称，dtId+1 匹配类型
      dishes.value = response.data.map((dish: Dish) => {
        const type = dishTypes.value.find(t => t.dtId === (dish.dtId + 1))
        return {
          ...dish,
          dtId: dish.dtId + 1, // 直接修正dtId，后续所有操作都用修正后的
          typeName: type ? type.dtName : '未知类型'
        }
      })
    } else {
      ElMessage.error(response.message || '获取菜品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取菜品类型列表
const fetchDishTypes = async () => {
  try {
    const response = await dishTypeApi.getDishTypes()
    if (response.code === 200) {
      dishTypes.value = response.data
    } else {
      ElMessage.error(response.message || '获取菜品类型列表失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品类型列表失败')
    console.error(error)
  }
}

// 状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'success'
    case 1: return 'warning'
    case 2: return 'info'
    default: return ''
  }
}

// 获取状态标签文本
const getStatusLabel = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status)
  return option ? option.label : ''
}

// 添加按钮处理
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑按钮处理
const handleEdit = (row: Dish) => {
  dialogType.value = 'edit'
  // 编辑时dtId已修正，无需再+1
  form.value = { ...row }
  dialogVisible.value = true
}

// 重置搜索条件
const resetSearch = () => {
  searchQuery.value = ''
  filterType.value = ''
  filterStatus.value = ''
}

// 图片上传前的验证
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 表单提交处理
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (!form.value.dtId) {
          ElMessage.error('请选择菜品类型')
          return
        }
        // 提交时dtId-1还原为后端需要的编号
        const dishData = {
          dishImage: form.value.dishImage,
          dishName: form.value.dishName,
          price: form.value.price,
          dishStatus: form.value.dishStatus,
          dtId: form.value.dtId - 1,
          dishDescribe: form.value.dishDescribe
        }
        if (dialogType.value === 'add') {
          // 创建新菜品
          const response = await dishApi.createDish(dishData)
          if (response.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            await fetchDishes()
          } else {
            ElMessage.error(response.message || '添加失败')
          }
        } else {
          // 编辑菜品
          const response = await dishApi.updateDish(form.value.dishId, dishData)
          if (response.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            await fetchDishes()
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
        console.error(error)
      }
    }
  })
}

// 自定义上传
const customUpload = async (options: any) => {
  try {
    // TODO: 实现文件上传
    // const formData = new FormData()
    // formData.append('file', options.file)
    // const response = await fetch('/api/upload', {
    //   method: 'POST',
    //   body: formData
    // })
    // const data = await response.json()
    // form.value.dishImage = data.url
    
    // 临时模拟上传成功
    const reader = new FileReader()
    reader.readAsDataURL(options.file)
    reader.onload = () => {
      form.value.dishImage = reader.result as string
    }
  } catch (error) {
    ElMessage.error('上传失败')
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    dishId: 0,
    dishImage: '',
    dishName: '',
    price: 0,
    dishStatus: 0,
    dtId: undefined,
    dishDescribe: ''
  }
}

// 图片预览处理
const handlePreview = (row: Dish) => {
  // 这里可以添加额外的预览逻辑如果需要
}

// 页面加载时获取数据
onMounted(async () => {
  // 先获取类型列表，再获取菜品列表
  await fetchDishTypes()
  await fetchDishes()
})

const OSS_PREFIX = 'https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/'
const ossUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return OSS_PREFIX + url.replace(/^@/, '')
}
</script>

<style scoped>
.dish-information-management-container {
  margin-left: 200px;
  margin-top: 45px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.dish-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  min-width: 800px;
}

.dish-table th,
.dish-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  color: #333;
  vertical-align: middle;
}

.dish-table th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
}

.dish-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.dish-table tbody tr:hover {
  background-color: #f5f5f5;
}

.actions-column {
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 100px;
  height: 60px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dish-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.1);
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-select) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .dish-information-management-container {
    margin-left: 0;
    width: 100%;
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
  }

  .title {
    width: 100%;
    text-align: center;
  }

  .search-area {
    .el-row {
      margin: 0 !important;
    }
    
    .el-col {
      padding: 0 !important;
      margin-bottom: 10px;
    }
  }

  .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style> 